package org.example.controller;

import org.example.exception.AppException;
import org.example.model.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //我们暂时不管请求方法，使用@RequestMapping允许任意的请求方法
    //登录接口
    //POST /api/user/login
    //{"username":"abc","password":"123"}
    @RequestMapping("/login")
    public Object login(@RequestBody User user,
                        HttpServletRequest req){
        //1.根据账号查询数据库的用户，不存在报错
        User params = new User();//只根据账号查
        params.setUsername(user.getUsername());
        //查询出来的用户
        User exist = userService.selectOne(params);
        //查不到，就是账号不存在
        if(exist == null){
            throw new AppException("账号不存在");
        }
        //2.校验密码，不一致就报错
        if(!exist.getPassword().equals(user.getPassword())){
            throw new AppException("账号或密码错误");
        }
        //3.校验通过：登录成功（创建session，保存用户信息）
        HttpSession session = req.getSession();
        //保存用户信息：注意键要和拦截器校验的键一致，保存数据库查出来的用户
        session.setAttribute("user", exist);

        return null;//统一响应会封装{success: true}
    }

    //注销接口
    //GET /api/user/logout
    @RequestMapping("/logout")
    public Object logout(HttpSession session){
        session.invalidate();
        return null;
    }

    //查询用户列表（表格）
    //GET /api/user/query
    @RequestMapping("/query")
    public Object query(){
        List<User> users = userService.query();
        return users;
    }

    //新增用户（也属于注册的功能）
    //如果账号已存在，插入就会报错（建议：尽量不要在数据库报错，在前置逻辑中，校验一下）
    //POST /api/user/register
    //{"username":"aaa","password":"","nickname":"","email":"","createTime":""}
    @RequestMapping("/register")
    public Object register(@RequestBody User user){
        int n = userService.register(user);
        return null;
    }

    //获取用户详情（修改用户时，先查询）
    //GET /api/user/queryById?id=xxx
    public Object queryById(Integer id){
        User user = userService.queryById(id);
        return user;
    }

    //修改用户
    //POST /api/user/update
    //{"id":1,"username":"aaa","password":"","nickname":"","email":"","createTime":""}
    @RequestMapping("/update")
    public Object update(@RequestBody User user){
        int n = userService.update(user);
        return null;
    }

    //删除用户（一个或多个）
    //GET /api/user/delete?ids=xxx&ids=xxx
    @RequestMapping("/delete")
    public Object delete(@RequestParam List<Integer> ids){
        int n = userService.delete(ids);
        return null;
    }

}
